import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Set;
import java.util.TreeSet;


public class ItemTxt2xml {

    final static File WORK_DIR = new File("C:/tmp/x/items");
    final static File SRC_FILE = new File(WORK_DIR,"items.txt");
    final static File DEST_FILE = new File(WORK_DIR,"items.xml");
    final static String NL = System.getProperty("line.separator");
    
    static BufferedReader in  = null;
    static BufferedWriter out = null;

    public static void main ( String[] args ) throws Exception {
        try {
            in = new BufferedReader(new FileReader(SRC_FILE));
            out = new BufferedWriter(new FileWriter(DEST_FILE));
            out.write("    <items>\n");
            String line = null;
            
            while ( (line = in.readLine()) != null )
                processInLine(line);
            
            out.write("    </items>" + NL);
        }
        finally {
            if ( in != null )
                try { in.close(); } catch ( Exception ex ) {};
            if ( out != null )
                try { out.close(); } catch ( Exception ex ) {};
        }
    }

// Slippers of Agility  Slippers of Agility     -   150     -   ,   Goblin Shop, Sena The Accessorizer
// Sobi Mask    Sobi Mask   -   325     -   , , , , ,   Goblin Laboratory, Cache of the Quel'thelan, Cache of the Quel'thelan
// Lothar's Edge    Lothar's Edge   1.100   3.400   ,   -   Ancient Weaponry
    private static void processInLine ( String line ) throws Exception {
        String[] toks = line.split("\t");
        if ( toks == null || toks.length != 7 )
            throw new Exception("wrong Tokens got!");
        // name = 0, recipe = 2, total = 3, shops = 6
        out.write("        <item ");
        out.write("name=\""         + toks[0].trim() + "\" ");
        out.write("recipe_costs=\"" + getIntVal(toks[2]) + "\" ");
        out.write("total_costs=\""  + getIntVal(toks[3]) + "\"");
        out.write(">" + NL);
        out.write("            <shops>" + NL);
        String[] shops = toks[6].split(",");
        Set<String> shopSet = new TreeSet<String>();
        for ( String shop : shops ) {
            shop = shop.trim();
            shopSet.add(shop);
        }
        for ( String shop : shopSet ) {
            out.write("                <shop name=\"" + shop + "\"/>" + NL);
        }
        out.write("            </shops>" + NL);
        out.write("        </item>" + NL);
    }

    private static int getIntVal ( String s ) {
        int res = 0;
        s = s.trim().replace(".","");
        try {
            res = Integer.parseInt(s);
        }
        catch ( NumberFormatException nfe ) {
        }
        return res > 0 ? res : 0;
    }

}
